package com.mayflygeek.mayflyask.util.mailutils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mayflygeek.mayflyask.common.MailConfigInfo;
/**
 * @author 蝈蝈 
 * @email guodefu909@126.com
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * 邮件发送类
 */
public class SimpleMailSender{
	
	private static Logger log = LoggerFactory.getLogger(SimpleMailSender.class);
	
	private SimpleMailSender() {
	}
	
	public static boolean sendMail(MailSenderInfo mailInfo) {
		// 判断是否需要身份认证
		MyAuthenticator authenticator = null;
		MailConfigInfo mailConfigInfo = mailInfo.getMailConfigInfo();
		// 如果需要身份认证，则创建一个密码验证器
		if (mailConfigInfo.isValidate()) {
			authenticator = new MyAuthenticator(mailConfigInfo.getUserName(), mailConfigInfo.getPassword());
		}
		// 用邮件服务器地址，端口，是否需要身份验证，构造一个Properties
		Properties pro = mailInfo.getProperties();
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getInstance(pro, authenticator);
		// 开启Session的debug模式，可以查看到程序发送Email的运行状态
		sendMailSession.setDebug(mailInfo.isDebug());
		try {
			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 创建邮件发送者，设置邮件发送者
			Address from = new InternetAddress(mailConfigInfo.getFromAddress(), mailConfigInfo.getFromUserName());
			mailMessage.setFrom(from);
			// 创建邮件接收者，设置邮件接收者
			Address to = new InternetAddress(mailInfo.getToAddress());
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			// 设置客户端显示的发信时间
			mailMessage.setSentDate(new Date());
			// 设置邮件消息的主题
			mailMessage.setSubject(mailInfo.getSubject());

			if (mailInfo.isHtmlMail()) {
				// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
				Multipart mainPart = new MimeMultipart();
				// 创建一个包含HTML内容的MimeBodyPart
				BodyPart mimeBody = new MimeBodyPart();
				// 设置HTML内容
				mimeBody.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
				mainPart.addBodyPart(mimeBody);
				// 将MiniMultipart对象设置为邮件内容
				mailMessage.setContent(mainPart);
			} else {
				// 设置文本邮件消息的主要内容
				mailMessage.setText(mailInfo.getContent());
			}

			// 发送邮件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException e) {
			log.error("邮件发送失败！");
			log.error(e.getMessage(), e);
		} catch (UnsupportedEncodingException e) {
			log.error("邮件发送失败，不支持的编码格式！");
			log.error(e.getMessage(), e);
		}
		return false;
	}

}
